package com.zyjedu.mvcframework.servlet;

import com.zyjedu.mvcframework.annotation.ZYJAutowired;
import com.zyjedu.mvcframework.annotation.ZYJController;
import com.zyjedu.mvcframework.annotation.ZYJRequestMapping;
import com.zyjedu.mvcframework.annotation.ZYJRequestParam;
import com.zyjedu.mvcframework.annotation.ZYJService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zyj
 */
public class ZYJDispatcherServlet extends HttpServlet {

    private static final Logger LOGGER = LoggerFactory.getLogger(ZYJDispatcherServlet.class);

    private Properties properties = new Properties();

    /**
     *  保存扫描到的所有类
     */
    private List<String> classNames = new ArrayList<>();

    /**
     * 初始化一个IOC容器
     */
    private Map<String, Object> ioc = new HashMap<>();

    /**
     * 初始化 handlerMapping
     */
    //private Map<String, Object> handlerMapping = new HashMap<>();

    private List<Handler> handlerMapping = new ArrayList<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doDispatch(req, resp);
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) {
        try {
            Handler handler = getHandler(req);
            if (handler == null) {
                //如果没有匹配上，返回404错误
                resp.getWriter().write("404 Not Found ~");
                return;
            }

            //获取方法的参数列表
            Class<?>[] parameterTypes = handler.method.getParameterTypes();
            //保存所有需要自动赋值的参数值
            Object[] paramValues = new Object[parameterTypes.length];

            Map<String, String[]> params = req.getParameterMap();
            for (Map.Entry<String, String[]> param : params.entrySet()) {
                String value = Arrays.toString(param.getValue()).replaceAll("\\[|\\]","").replaceAll(",\\s", ",");

                //如果找到匹配的对象，则开始填充参数值
                if (!handler.paramIndexMapping.containsKey(param.getKey())) {
                    continue;
                }
                int index = handler.paramIndexMapping.get(param.getKey());
                paramValues[index] = convert(parameterTypes[index], value);
            }
            //设置方法中的request和response对象
            int reqIndex = handler.paramIndexMapping.get(HttpServletRequest.class.getName());
            paramValues[reqIndex] = req;
            int respIndex = handler.paramIndexMapping.get(HttpServletResponse.class.getName());
            paramValues[respIndex] = resp;

            handler.method.invoke(handler.controller, paramValues);
        } catch (Exception e) {
            try {
                resp.getWriter().write("500 Exception" + Arrays.toString(e.getStackTrace()));
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }

    /**
     * Handler 记录controller中的RequestMapping 和 Method 的对应关系
     */
    private class Handler {
        /**
         * 保存方法对应的实例
         */
        protected Object controller;
        /**
         * 保存映射的方法
         */
        protected Method method;
        protected Pattern pattern;
        /**
         * 参数顺序
         */
        protected Map<String, Integer> paramIndexMapping;

        /**
         * 构造一个handler 基本的参数
         * @param pattern
         * @param controller
         * @param method
         */
        public Handler(Pattern pattern, Object controller, Method method) {
            this.controller = controller;
            this.pattern = pattern;
            this.method = method;

            paramIndexMapping = new HashMap<>();
            putParamIndexMapping(method);
        }

        private void putParamIndexMapping(Method method) {
            //提取方法中加了注解的参数
            Annotation[][] annotations = method.getParameterAnnotations();
            for (int i = 0; i < annotations.length; i++) {
                for (Annotation a : annotations[i]) {
                    if (a instanceof ZYJRequestParam) {
                        String paramName = ((ZYJRequestParam) a).value();
                        if (!"".equals(paramName.trim())) {
                            paramIndexMapping.put(paramName, i);
                        }
                    }
                }
            }
            //提取方法中的request和response参数
            Class<?>[] parameterTypes = method.getParameterTypes();
            for (int i = 0; i < parameterTypes.length; i++) {
                Class<?> type = parameterTypes[i];
                if (type == HttpServletRequest.class || type == HttpServletResponse.class) {
                    paramIndexMapping.put(type.getName(), i);
                }
            }
        }
    }

    private Handler getHandler(HttpServletRequest request) {
        if (handlerMapping.isEmpty()) {
            return null;
        }
        String url = request.getRequestURI();
        String contextPath = request.getContextPath();
        url = url.replace(contextPath, "").replaceAll("/+", "/");

        for (Handler handler : handlerMapping) {
            try {
                Matcher matcher = handler.pattern.matcher(url);
                //如果没有匹配上继续下一个匹配
                if (!matcher.matches()) {
                    continue;
                }
                return handler;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public void init(ServletConfig config) {
        LOGGER.info("**************");

        //1、加载配置文件
        doLoadContextConfig(config.getInitParameter("contextConfigLocation"));

        //2、扫描所有相关的类
        doScanner(properties.getProperty("scanPackage"));

        //3、实例化所有相关的类到IOC容器中
        doInstance();

        //4、完成自动化注入的过程
        doAutowired();

        //5、初始化HandlerMapping
        initHandlerMapping();

    }

    /**
     * 初始化HandlerMapping
     */
    private void initHandlerMapping() {
        if (ioc.isEmpty()) {
            return;
        }
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Class<?> classZZ = entry.getValue().getClass();

            //判断
            if (!classZZ.isAnnotationPresent(ZYJController.class)) {
                continue;
            }

            String baseUrl = "";
            if (classZZ.isAnnotationPresent(ZYJRequestMapping.class)) {
                ZYJRequestMapping requestMapping = classZZ.getAnnotation(ZYJRequestMapping.class);
                baseUrl = requestMapping.value();
            }

            //只处理公共的方法
            for (Method method : classZZ.getMethods()) {
                if (!method.isAnnotationPresent(ZYJRequestMapping.class)) {
                    continue;
                }

                ZYJRequestMapping requestMapping = method.getAnnotation(ZYJRequestMapping.class);
                String regex = ("/" + baseUrl + "/" + requestMapping.value()).replaceAll("/+", "/");

                //封装一个包含了url,instance, method 的对象
                //handlerMapping.put(url, method);

                Pattern pattern = Pattern.compile(regex);
                handlerMapping.add(new Handler(pattern, entry.getValue(), method));

                System.out.println("-----Mapping: " +  regex  + "=== " + method);
            }
        }
    }

    /**
     * 完成自动化注入的过程
     */
    private void doAutowired() {
        if (ioc.isEmpty()) {
            return;
        }

        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            //不管有多少个字段，都取出来，然后强制赋值
            Field[] fields = entry.getValue().getClass().getDeclaredFields();

            for (Field field : fields) {
                if (!field.isAnnotationPresent(ZYJAutowired.class)) {
                    continue;
                }
                ZYJAutowired autowired = field.getAnnotation(ZYJAutowired.class);
                String beanName = autowired.value().trim();

                if ("".equals(beanName)) {
                    beanName = field.getType().getName();
                }

                //强制赋值
                field.setAccessible(true);

                try {
                    field.set(entry.getValue(), ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 实例化所有相关的类到IOC容器中
     */
    private void doInstance() {
        if (classNames.isEmpty()) {
            return;
        }

        try {
            for (String className : classNames) {
                Class<?> classZZ = Class.forName(className);

                /*
                   接下来完成初始化，只给加了指定注解的类初始化

                   比如：只给添加了 @ZYJController 或者 @ZYJService注解的才给初始化
                 */
                if (classZZ.isAnnotationPresent(ZYJController.class)) {
                    /*
                       就是对象存到一个Map中，而这个Map需要有 key-value

                       1、默认类名首字母小写
                       2、自定义
                       3、自动识别接口类型，完成赋值
                     */

                    //key 为类名首字母小写
                    String key = lowerFirstCase(classZZ.getSimpleName());
                    Object instance = classZZ.newInstance();
                    ioc.put(key, instance);
                } else if (classZZ.isAnnotationPresent(ZYJService.class)) {
                    //1、默认类名首字母小写

                    // 2、自定义
                    ZYJService service = classZZ.getAnnotation(ZYJService.class);
                    String beanName = service.value();
                    if ("".equals(beanName.trim())) {
                        beanName = lowerFirstCase(classZZ.getSimpleName());
                    }
                    Object instance = classZZ.newInstance();
                    ioc.put(beanName, instance);

                    //3、自动识别接口类型，完成赋值
                    Class<?>[] interfaces = classZZ.getInterfaces();

                    //如果有多个实现类，要么自定义名字，要么抛异常
                    for (Class<?> i : interfaces) {
                        ioc.put(i.getName(), instance);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 扫描所有相关的类
     * @param scanPackage
     */
    private void doScanner(String scanPackage) {
        URL url = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.", "/"));
        File classDir = new File(url.getFile());

        for (File file : classDir.listFiles()) {
            if (file.isDirectory()) {
                doScanner(scanPackage + "." + file.getName());
            } else {
                String className = scanPackage + "." + file.getName().replace(".class", "");
                classNames.add(className);
            }
        }
    }

    /**
     * 加载配置文件
     * @param location
     */
    private void doLoadContextConfig(String location) {
        InputStream stream = this.getClass().getClassLoader().getResourceAsStream(location);
        try {
            properties.load(stream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 把类名首字母小写
     * @param className
     * @return
     */
    private String lowerFirstCase(String className) {
        char[] chars = className.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }

    private Object convert(Class<?> type, String value) {
        if (Integer.class == type) {
            return Integer.valueOf(value);
        }
        return value;
    }
}
